﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MVVM.Model;

namespace MVVM.Repository {
    internal sealed class UnitOfWork : IUnitOfWork, IDisposable {

        //A Static instance of the Linq Data Context
        private static DataModel _service;

        //The default constructor
        public UnitOfWork() {
            if (_service == null) {
                _service = new DataModel();
            }
        }

        //Add a new entity to the model
        public void Add<T>(T _entity) where T : class {
            var table = _service.GetTable<T>();
            table.InsertOnSubmit(_entity);
        }
        //Delete an existing entity from the model
        public void Delete<T>(T _entity) where T : class {
            var table = _service.GetTable<T>();
            table.DeleteOnSubmit(_entity);
        }
        //Update an existing entity
        public void Update<T>(T _entity) where T : class {
            var table = _service.GetTable<T>();
            table.Attach(_entity, true);
        }
        //Commit all the pending changes in the data context
        public void Commit() {
            _service.SubmitChanges();
        }
        //Get the entire Entity table
        public IList<T> GetAll<T>() where T : class {
            return _service.GetTable<T>().ToList();
        }
        //Get by query
        public IList<T> GetByQuery<T>(Expression<Func<T, bool>> query) where T : class {
            return _service.GetTable<T>().Where(query).ToList();
        }
        //Get the first occurence that reflect the Linq Query
        public T GetById<T>(Func<T, bool> _condition) where T : class {
            return _service.GetTable<T>().Where(_condition).FirstOrDefault();
        }

        #region IDisposable Members

        public void Dispose() {
            _service.Dispose();
        }

        #endregion
    }
}
